package com.ithema.reggie.service.impl;

import com.ithema.reggie.common.R;
import com.ithema.reggie.entity.ShoppingCart;
import com.ithema.reggie.mapper.ShoppingCartMapper;
import com.ithema.reggie.service.ShoppingCartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class ShoppingCartServiceImpl implements ShoppingCartService {

    @Autowired
    ShoppingCartMapper shoppingCartMapper;;

    @Override
    public R add2Cart(ShoppingCart paramCart) {

        //1.通过菜品id或者套餐id 联合用户去数据库数据中查询是否有无添加过
        ShoppingCart shoppingCart = shoppingCartMapper.findByDishIdOrSetmealIdWithUserId(paramCart);

        //2.若没有添加过，就保存
        if (shoppingCart == null){
            shoppingCart = paramCart;

            shoppingCart.setNumber(1);
            shoppingCart.setCreateTime(LocalDateTime.now());

            shoppingCartMapper.save(shoppingCart);
        }else {
            //3.若添加过，则修改数量保存
            shoppingCart.setNumber(shoppingCart.getNumber() + 1);

            shoppingCartMapper.update(shoppingCart);
        }

        //4.页面上要展示购物车项对应的菜品或者套餐数据，因此返回购物项
        return R.success(shoppingCart);
    }

    //根据用户id查看购物车
    @Override
    public R showCart(Long userId) {

        //调用mapper，通过用户id查询所有的购物项
        List<ShoppingCart> carts = shoppingCartMapper.findAllByUserId(userId);
        return R.success(carts);
    }

    @Override
    public R cleanCart(Long userId) {

        //调用mapper清空购物车
        shoppingCartMapper.delectByUserId(userId);
        return R.success(null);
    }

}
